#include "epoller.h"

namespace zh
{
    Epoller::Epoller(int maxEvents) : m_epollFD(epoll_create(512)), m_events(maxEvents)
    {
        assert(m_epollFD >= 0 && !m_events.empty());
    }

    Epoller::~Epoller()
    {
        close(m_epollFD);
    }

    bool Epoller::addFD(int fd, uint32_t events)
    {
        if (fd < 0)
        {
            return false;
        }
        epoll_event event {0};
        event.data.fd = fd;
        event.events  = events;
        return 0 == epoll_ctl(m_epollFD, EPOLL_CTL_ADD, fd, &event);
    }

    bool Epoller::modifyFD(int fd, uint32_t events)
    {
        if (fd < 0)
        {
            return false;
        }
        epoll_event event {0};
        event.data.fd = fd;
        event.events  = events;
        return 0 == epoll_ctl(m_epollFD, EPOLL_CTL_MOD, fd, &event);
    }

    bool Epoller::deleteFD(int fd)
    {
        if (fd < 0)
        {
            return false;
        }
        epoll_event event {0};
        return 0 == epoll_ctl(m_epollFD, EPOLL_CTL_DEL, fd, &event);
    }

    int Epoller::wait(int timeout)
    {
        return epoll_wait(m_epollFD, &m_events[0], static_cast<int>(m_events.size()), timeout);
    }

    int Epoller::getEventFD(size_t index) const
    {
        assert(index >= 0 && index < m_events.size());
        return m_events[index].data.fd;
    }

    uint32_t Epoller::getEvents(size_t index) const
    {
        assert(index >= 0 && index < m_events.size());
        return m_events[index].events;
    }
} // namespace zh